package com.tceasy.gateway.aop;

import com.tceasy.common.utils.id.IdBuilder;
import com.tceasy.gateway.api.BusinessFailException;
import com.tceasy.gateway.api.RequestParamUtil;
import com.tceasy.gateway.api.SystemFailException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.tceasy.gateway.api.Response.SYSTEM_FAIL;

/**
 * Created by zhanghuan on 2016/4/13.
 */
@Component
@Aspect
public class GatewayAspect {

    Logger logger= LoggerFactory.getLogger(GatewayAspect.class);

    @Around("execution(* com.tceasy.gateway.controller.*.*(..))&&@annotation(org.springframework.web.bind.annotation.ResponseBody)")
    public Object controllerCheck(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String url = request.getRequestURL().toString();
        String paramStr= null;
        String headers=null;
        try {
            paramStr = RequestParamUtil.getParam(request);
            headers=RequestParamUtil.getHearders(request);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        logger.info("请求URL：{},param:{},headers:{}",new Object[]{url,paramStr,headers});
        Check classCheck= (Check) pjp.getSignature().getDeclaringType().getAnnotation(Check.class);
        /*拦截类上含有check注解的controller*/
        if(classCheck==null){
            try{
                MDC.put("logId", IdBuilder.getID());
                return pjp.proceed();
            }finally {
                MDC.clear();
            }

        }
        try {
            MDC.put("logId", IdBuilder.getID());
            return pjp.proceed();
        }catch (SystemFailException sys){
            logger.error(sys.getMessage());
            return sys.toJson();
        }catch (BusinessFailException business){
            logger.error(business.getMessage());
            return business.toJson();
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return SYSTEM_FAIL(e.getMessage()).toJson();
        }finally {
            MDC.clear();
        }

    }
}
